package com.phonebrand.service;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.home.mylib.RestClient;
import com.phonebrand.convert.ConvertJsonToModel;



public class PhoneService {
	private static final String LOG_TAG = "PhoneService";
	//private final String PHONE_URL = "http://203.150.20.37/imake/rest/numbering";	
//	private final int PHONE_TIMEOUT = 1500;

			
	private final String CROSS_URL = "http://thebluecode.co.th/bokber/call.php";
//	private final int CROSS_TIMEOUT = 5000;
	
	private static String strURL;
	
	private static PhoneService mInstance= null; 	
	public static synchronized PhoneService getInstance(){         
	
		if(null == mInstance){                 
			mInstance = new PhoneService();         
		}         
		return mInstance;     
	}

	public String getBrand(String phoneNum) {
		try {
			Log.d(LOG_TAG,CROSS_URL);
			if (strURL == null || strURL.equals("")) {
				strURL = getURL();
			} 
			
			//   MyHttpConnection con = new MyHttpConnection();
		    // List<NameValuePair> pl = new ArrayList<NameValuePair>();
			phoneNum = phoneNum.replace("-", "");
			phoneNum = phoneNum.replace(" ", "");
			String url = strURL+"/"+phoneNum.substring(0,2) +"/"+phoneNum.substring(2);		     		    
		     Log.i(LOG_TAG, "getBrand url "+url);
		     RestClient resClient = new RestClient(url);		     
		     resClient.Execute(RestClient.RequestMethod.GET);
		     String result = String.valueOf(resClient.getResponse());
		     
		     
		     Log.i(LOG_TAG, "getBrand result "+result);
		     JSONObject obj = new JSONObject(result);	    		   	    	 
	    	 String brand =ConvertJsonToModel.getInstance().jsonToBrandName(obj);
	    	 return brand.replace("&amp;", "&");
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(LOG_TAG, " getBrand() "+e.toString());	
			return "";
		}
		
	}
	
	
	public String getURL() {
		try {						
			//   MyHttpConnection con = new MyHttpConnection();
		    // List<NameValuePair> pl = new ArrayList<NameValuePair>();					     		   		     
		     RestClient resClient = new RestClient(CROSS_URL);		     
		     resClient.Execute(RestClient.RequestMethod.GET);		     
		     String result = String.valueOf(resClient.getResponse());
		     
		     
		     Log.i(LOG_TAG, "getURL result "+result);
		     JSONArray obj = new JSONArray(result);	    		   	    	 
	    	 String directURL =obj.getString(0);
	    	 Log.i(LOG_TAG, "getURL directURL "+directURL);
	    	 return directURL;
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(LOG_TAG, " directURL() "+e.toString());	
			return "";
		}
		
	}
	
		
	
}
